<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>角色管理</title>
    <link rel="stylesheet" type="text/css" th:href="@{/plugins/layui/css/layui.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/css/common.css}"/>
    <link th:href="@{/plugins/jquery-ztree/3.5/css/metro/zTreeStyle.css}" rel="stylesheet"/>
    <script th:src="@{/plugins/jquery/jquery.min.js}" type="text/javascript" charset="utf-8"></script>
    <script th:src="@{/plugins/jquery-ztree/3.5/js/jquery.ztree.all-3.5.js}" type="text/javascript" charset="utf-8"></script>
</head>
<body>
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body layui-form layui-form-pane">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">角色名称</label>
                        <div class="layui-input-inline">
                            <input id="name" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">角色状态</label>
                        <div class="layui-input-inline">
                            <select name="status" id="status">
                                <option value="">所有</option>
                                <option value="0">正常</option>
                                <option value="1" >停用</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">开始时间</label>
                        <div class="layui-input-inline">
                            <input class="layui-input" id="startTime" name="startTime" placeholder="">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">结束时间</label>
                        <div class="layui-input-inline">
                            <input class="layui-input" id="endTime" name="endTime" placeholder="">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <div class="layui-input-inline" style="margin-top:5px;">
                            <button id="roleBtnSearch" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索
                            </button>
                            <button id="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-card">
            <div class="layui-card-body">
                <table id="roleTab" lay-filter="roleTab"></table>
            </div>
        </div>
        <html th:include="website/footer"></html>
    </div>

    <!-- 工具条 -->
    <script type="text/html" id="roleToolbar">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="addRole">
                <i class="layui-icon">&#xe654;</i>新增
            </button>
            <button class="layui-btn layui-btn-sm" lay-event="batchDelRole">
                <i class="layui-icon">&#xe640;</i>批量删除
            </button>
        </div>
    </script>

    <!-- 表格操作列 -->
    <script type="text/html" id="roleBar">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="setMenu">菜单权限</a>
    </script>

    <!-- 表单弹窗 -->
    <script type="text/html" id="roleForm">
        <form class="layui-form" lay-filter="roleForm" style="padding-top: 25px;">

            <input type="hidden" name="roleId" />

            <div class="layui-form-item">
                <label class="layui-form-label">角色名称：</label>
                <div class="layui-input-inline">
                    <input type="text" id="roleName" name="roleName" placeholder="请输入角色名称" lay-verify="roleName"
                           maxlength="12" class="layui-input" style="width:350px;">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">角色描述：</label>
                <div class="layui-input-inline">
                    <input type="text" id="roleDesc" name="roleDesc" placeholder="请输入角色描述"
                           maxlength="255" class="layui-input" style="width:350px;">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">父角色：</label>
                <div class="layui-input-inline">
                    <input type="text" id="fatherName" placeholder="请选择" class="layui-input" style="width:350px;">
                    <input type="text" id="fatherId" name="fatherId" class="layui-input" style="width:350px;">
                    <div id="info" style="display: none;">
                        <div id="roleTree" class="ztree"></div>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">状态：</label>
                <div class="layui-input-block">
                    <input type="radio" name="status" value="0" title="正常" checked/>
                    <input type="radio" name="status" value="1" title="停用"/>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="addRoleFrom">保存</button>
                    <button class="layui-btn layui-btn-primary" type="button" id="btnClose">取消</button>
                </div>
            </div>
        </form>
    </script>

    <!-- 菜单权限树 -->
    <script type="text/html" id="menuTreeForm">
        <form class="layui-form" lay-filter="menuTreeForm" style="padding-top: 25px;">

            <div class="layui-form-item">
                <label class="layui-form-label">菜单权限:</label>
                <div class="layui-input-inline">
                    <div id="menuTree" class="ztree"></div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="saveMenuForm">保存</button>
                    <button class="layui-btn layui-btn-primary" type="button" id="menuTreeClose">取消</button>
                </div>
            </div>
        </form>
    </script>


    <script th:src="@{/plugins/layui/layui.js}" type="text/javascript" charset="utf-8"></script>
    <script th:src="@{/js/main.js}" type="text/javascript" charset="utf-8"></script>
    <script th:src="@{/plugins/jquery-ztree/3.5/js/jquery.ztree.all-3.5.js}" charset="utf-8"></script>

    <script>
        layui.use(['form','table','layer','laydate','songCommon'], function(){
            var layer = layui.layer,$ = layui.$,
                laydate = layui.laydate,form =layui.form,
                table = layui.table,
                songCommon = layui.songCommon;

                // 日期控件渲染
                laydate.render({
                    elem: '#startTime'
                });
                laydate.render({
                    elem: '#endTime'
                });

                // 角色列表
                var array = [
                     {type: 'checkbox', fixed: 'left'}
                    ,{field:'roleName', title:'角色名称'}
                    ,{field:'roleDesc', title:'角色描述'}
                    ,{field:'status', templet : function(d) {
                            if (d.status === 0) {
                                return "<button class='layui-btn layui-btn-sm'>正常</button>";
                            } else {
                                return "<button class='layui-btn layui-btn-sm layui-btn-danger'>停用</button>";
                            }
                        }, title:'角色状态',align:'center'}
                    ,{field:'createTime', title:'创建时间'}
                    ,{field:'createAdmin', title:'创建人'}
                    ,{fixed: 'right', title:'操作', toolbar: '#roleBar',align:'center'}
                ];
                table.render({
                    elem: '#roleTab'
                    ,url:'/v1/role/roleList'
                    ,cellMinWidth: 80
                    ,title: '角色列表'
                    ,toolbar: '#roleToolbar'
                    ,defaultToolbar : ['filter']
                    ,limits : [10,30,60,90]
                    ,cols: [
                        array
                    ]
                    // ,even: true 开启隔行背景
                    ,text: {
                        none: '暂无相关数据'
                    }
                    ,id : 'roleTable'
                    ,page: true
            });

            // 搜索
            $("#roleBtnSearch").click(function () {
                var startTime  =  $("#startTime").val();
                var endTime =  $("#endTime").val();
                if (startTime !== "" && endTime !== "") {
                    if (startTime > endTime) {
                        songCommon.showFail("开始时间不能大于结束时间");
                        return;
                    }
                }
                table.reload('roleTable', {
                    where: {
                        roleName : $("#name").val(),
                        status : $("#status").val(),
                        startTime : $("#startTime").val(),
                        endTime : $("#endTime").val()
                    }
                });
            });

            // 重置
            $("#reset").click(function () {
                $("#name").val("");
                $("#status").val("");
                $("#startTime").val("");
                $("#endTime").val("")
                form.render();
            });

            table.on('tool(roleTab)', function(obj){
                var data = obj.data;
                if(obj.event === 'del'){
                   layer.confirm("您确定删除此数据？删除后无法恢复",{icon: 3, title:'提示'},function (index) {
                       var path = "/v1/role/deleteRoleById";
                       $.post(path,{
                           roleId : data.roleId
                       },function (res) {
                           if (res.code === 0) {
                               layer.msg("删除成功！");
                           } else {
                               layer.msg("删除失败！");
                           }
                       },"json");
                       layer.close(index);
                       reloadTab();
                   });
                } else if (obj.event === "edit") {
                    showEditModel(data);
                } else if (obj.event === "setMenu") {
                    showMenu(data);
                }
            });

            // 树形
            var setting = {
                check : {
                    enable: true,
                    chkStyle: "checkbox",
                    chkboxType: { "Y": "ps", "N": "ps" },
                    nocheckInherit: true
                },
                view: {
                    nameIsHTML: true,
                    showLine: true,
                    selectedMulti: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                }
            };
            // 展示权限弹框
            function showMenu(data) {
                var index = layer.open({
                    type: 1,
                    area: ['520px', '300px'], //宽高
                    maxmin: true,
                    title: "菜单权限列表",
                    content: $('#menuTreeForm').html(),
                    success: function () {

                        var path = '/v1/menu/getMenuTreeByRoleId?roleId=' + data.roleId
                        $.post(path, function (res) {
                            $.fn.zTree.init($("#menuTree"), setting, res);
                            $.fn.zTree.getZTreeObj("menuTree").expandAll(true);
                        }, "json");

                        form.on("submit(saveMenuForm)", function () {
                            var treeObj = $.fn.zTree.getZTreeObj("menuTree");
                            var nodes = treeObj.getCheckedNodes(true);
                            var menuIds = [];
                            for (var k in nodes) {
                                menuIds.push(nodes[k].id);
                            }
                            var path = "/v1/menu/addRoleMenus";
                            layer.load(2);
                            $.post(path, {
                                roleId: data.roleId,
                                menuIds: menuIds.join()
                            }, function (res) {
                                layer.closeAll('loading');
                                if (res.code === 0) {
                                    songCommon.showOk("分配菜单权限成功！");
                                } else if (res === 500) {
                                    songCommon.showFail(res.msg);
                                } else {
                                    songCommon.showFail("分配菜单权限失败");
                                }
                            }, "json");
                            layer.close(index);
                            return false;
                        });
                    }
                });
                $(document).on('click', '#menuTreeClose', function () {
                    layer.close(index);
                });
            }

            // 刷新表格
            function reloadTab () {
                table.reload('roleTable');
            }

            // 监听工具栏事件
            table.on('toolbar(roleTab)', function(obj){
                var layEvent = obj.event;
                var checkStatus = table.checkStatus(obj.config.id)
                    ,data = checkStatus.data; //获取选中的数据

                switch(layEvent) {

                    case 'addRole':
                        showEditModel();
                        break;

                    // 批量删除
                    case 'batchDelRole':
                        if (data.length === 0) {
                            layer.msg("请选择具体数据！", {time: 3000});
                            return
                        }
                        var ids = [];
                        for (var index in data) {
                            ids.push(data[index].roleId);
                        }
                        var path  = "/v1/role/batchDel";
                        var param = {
                            ids : ids.toString()
                        };
                        layer.confirm('您确定要删除选中的数据？删除后,不可恢复',{icon:3,title:"提示"},function(index) {
                            $.post(path, param, function (data) {
                                if (data.code === 0) {
                                    layer.msg("删除成功！");
                                    reloadTab();
                                }
                            }, "json");
                            layer.close(index);
                        });
                        break;
                };
            });

            // 树形
            var roleTreeSetting = {
                view: {
                    nameIsHTML: true,
                    showLine: true,
                    selectedMulti: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: treeOnClick
                }
            };

            function treeOnClick(event, treeId, treeNode) {
                $("#fatherName").val(treeNode.name);
                $("#fatherId").val(treeNode.id);
                $('#info').hide();
            }

            // 编辑框
            function showEditModel(data) {
                var index  = layer.open({
                    type: 1,
                    area: ['520px', '400px'], //宽高
                    maxmin: true,
                    title: data ? '修改角色' : '添加角色',
                    content: $('#roleForm').html(),
                    success : function (layero, index) {
                        var path = "/v1/role/addRole";

                        var roleTreePath = "/v1/role/getRoleTree";
                        $.post(roleTreePath, function (res) {
                            $.fn.zTree.init($("#roleTree"), roleTreeSetting, res);
                            var treeObj = $.fn.zTree.getZTreeObj("roleTree");
                            treeObj.expandAll(true);

                            // 回显数据
                            if (data) {

                                var currentNode = treeObj.getNodeByParam("id",data.roleId);
                                var childNodes = treeObj.transformToArray(currentNode);

                                for (var i = 0, k = childNodes.length; i < k; i++) {
                                    treeObj.setChkDisabled(nodes[i], true);
                                }

                                form.val('roleForm', data);
                                $("input[name='status'][value='0']").attr("checked", data.status == 0 ? true : false);
                                $("input[name='status'][value='1']").attr("checked", data.status == 1 ? true : false);
                                path = "/v1/role/updateRole";
                            }

                        }, "json");

                        $("#fatherName").bind("click",function () {
                            $('#info').show();
                        });

                        form.render();

                        //监听提交
                        form.on('submit(addRoleFrom)', function (rowData) {
                            layer.load(2);
                            $.post(path, rowData.field, function(ajaxData) {
                                layer.closeAll('loading');
                                if (ajaxData.code === 0) {
                                    layer.msg("操作成功！");
                                    reloadTab();
                                } else {
                                    layer.msg(ajaxData.msg, {icon: 2});
                                }
                            }, "json");
                            layer.close(index);
                            return false;
                        });
                    }
                });
                $(document).on('click','#btnClose',function(){
                    layer.close(index);
                });
            }

            // 表单校验
            form.verify({
                roleName : function (value,item) {
                    if (value === "") {
                        return "不允许为空";
                    }
                    if (value.length < 2) {
                        return "最少输入两个字符";
                    }
                    if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                        return '用户名不能有特殊字符';
                    }
                    if(/(^\_)|(\__)|(\_+$)/.test(value)){
                        return '用户名首尾不能出现下划线\'_\'';
                    }
                    if(/^\d+\d+\d$/.test(value)){
                        return '用户名不能全为数字';
                    }
                }
            })

        });
    </script>

</body>
</html>                                                                                                                                                                                                                                                                                                                                                                          